console.log('*** open net init ***');

var ws = null,
	plusBackKey = null,
	itoolInit = {
		back: true // 防止安卓 加载时关闭父页
	};

// H5 plus事件处理
function plusReady() {

	console.log('*** open net plusReady ***');
	ws = plus.webview.currentWebview();

	// 首页KEY
	_u_1p_datePlus(plus.webview.getLaunchWebview().id);

	/**
	 * 首页固定ID
	 * 刷新页面
	 * */

	// 默认原生跳转
	itoolInit.openNative = function(Url, title, header) {

		if(itoolInit.thiswebview) return console.log('已组织重复打开 URL ' + Url);

		itoolInit.back = false;

		console.log('************* webview key: ' + Url.split('?')[0] + ' ***************')

		itoolInit.thiswebview = plus.webview.create(Url, Url.split('?')[0], {
			titleNView: {
				progress: {
					color: '#3385ff',
					height: '2px',
				},
				backgroundColor: '#fff',
				titleText: title,
				titleColor: '#000',
				autoBackButton: true,
				splitLine: {
					color: '#ddd'
				}
			}
		}, {
			appmain: ws.appmain
		});
		
		itoolInit.thiswebview.setCssText(plus.storage.getItem(ws.appmain));

		// 关闭事件
		itoolInit.thiswebview.addEventListener('close', function() {
			itoolInit.back = true;
			itoolInit.thiswebview = null;
		});

		// 注册侧滑关闭
		if(plus.os.name != 'iOS') itoolInit.thiswebview.drag({
			direction: 'right',
			moveMode: 'followFinger'
		}, {
			view: ws.id,
			moveMode: 'silent'
		}, function(e) {
			//滑动到end执行mui.back()事件
			if(e.type == 'end' && e.result) {
				itoolInit.thiswebview.close();
			}
		});

		// 加载初始化脚本
		itoolInit.thiswebview.setJsFile("_www/bll/pageinit/init.js");

		// 执行动画
		itoolInit.thiswebview.show('slide-in-right');
	}

	if(location.href.indexOf('zhihu.com')) {
		var style = document.createElement('style');
		document.getElementsByTagName('head')[0].appendChild(style);
		var s = document.styleSheets[document.styleSheets.length - 1];
		s.insertRule('.MobileAppHeader,.OpenInAppButton,.DownloadGuide,.ViewAllInappButton,[data-za-detail-view-path-module=ExternalAdItem]{display: none !important; }', s.cssRules.length);
	}

	// 拦截所有网络请求
	ws.overrideUrlLoading({
		mode: 'match'
	}, function(e) {
		
		console.log('拦截所有网络请求')
		
		itoolInit.openNative(e.url, e.title);
	});

	var ___back = function() {

		if(ws.id == ws.appkey && itoolInit.back) {
			itoolInit.back = true;
			ws.hide('slide-out-bottom', 200);
		} else {
			if(itoolInit.back) {
				ws.close('slide-out-right');
			} else {
				itoolInit.thiswebview.close('slide-out-right');
			}
		}

	};

	// Android处理返回键
	plusBackKey.addEventListener('backbutton', ___back, false);

	if(ws.id == ws.appkey) {

		var ms = (/Html5Plus\/.+\s\(.*(Immersed\/(\d+\.?\d*).*)\)/gi).exec(navigator.userAgent);

		if(ms && ms[2]) {
			document.body.style.marginTop = ms[2] + 'px';
		}

		var ___clearmuibackbot = false;

		var ___muiback = setInterval(function() {
			try {
				if(mui) {
					mui.back = ___back;
					if(!___clearmuibackbot) {
						___clearmuibackbot = true;
						setTimeout(function() {
							clearInterval(___muiback);
						}, 1500);
					}
				}
			} catch(e) {
				console.log(e)
			}

		}, 500);

		if(!___clearmuibackbot) {
			___clearmuibackbot = true;
			setTimeout(function() {
				clearInterval(___muiback);
			}, 3000);
		}

	}

};

if(window.plus) {
	plusReady();
} else {
	document.addEventListener('plusready', plusReady, false);
}

// 修改 plus 对象
function _u_1p_datePlus(mainKey) {

	var $ = plus.webview;

	plusBackKey = plus.key;

	plus.key = null;

	var pw = {

		// 关闭页面处理
		close: function(id, aniClose, duration, extras) {
			if(mainKey == id)
				return $.close(id + 'webview', aniClose, duration, extras);
			return $.close(id, aniClose, duration, extras);
		},

		// 获取首页
		getLaunchWebview: function() {
			return $.getWebviewById('appMain');
		},

		// 隐藏页面
		hide: function(id, aniHide, duration, extras) {
			if(mainKey == id)
				return $.hide(id + 'webview', aniClose, duration, extras);
			return $.hide(id, aniClose, duration, extras);
		},

		// 创建并打开页面
		open: function(url, id, styles, aniShow, duration, showedCB) {
			if(mainKey == id)
				return $.open(url, id + 'webview', styles, aniShow, duration, showedCB);
			return $.open(url, id, styles, aniShow, duration, showedCB);
		},

		// 显示Webview窗口
		show: function(id, aniShow, duration, showedCB, extras) {
			if(mainKey == id)
				return $.show(id + 'webview', aniShow, duration, showedCB, extras);
			return $.show(id, aniShow, duration, showedCB, extras);
		},

		// 创建页面
		create: function(url, id, styles, extras) {
			if(mainKey == id)
				return $.create(url, id + 'webview', styles, extras);
			return $.create(url, id, styles, extras);
		},

		// 获取所有页面
		all: function() {

			var vs = $.all(),
				val = [];

			for(var i = 0; i < vs.length; i++) {
				if(vs[i].id != mainKey) val.push(vs[i]);
			}

			return val;

		}
	};

	plus.webview.getLaunchWebview = function() {
		return plus.webview.getWebviewById(ws.appmain);
	};

	plus.webview.getSecondWebview = function() {
		return plus.webview.getWebviewById(ws.appmain);
	};

}

var Ajax = {
	get: function(url, fn) {
		// XMLHttpRequest对象用于在后台与服务器交换数据   
		var xhr = new XMLHttpRequest();
		xhr.open('GET', url, true);
		xhr.onreadystatechange = function() {
			// readyState == 4说明请求已完成
			if(xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
				// 从服务器获得数据 
				fn.call(this, xhr.responseText);
			}
		};
		xhr.send();
	}
}

Ajax.get('https://app.help-itool.com/Content/app/WebView.js', function(e) {
	var script = document.createElement('script');
	script.setAttribute('type', 'text/javascript');
	script.innerHTML = e;
	document.getElementsByTagName('head')[0].appendChild(script);

});